/*
ConnectionManagerTest
*/

ConnectionManager{

	var parent, connections;
	
	*new{|parent|
		^super.newCopyArgs(parent).init;
	}
	
	init{
		connections = Dictionary.new;	
	}
	
	soundPlayed{|sourceName|
		
		var sourceList, connection;
	
		sourceList = connections.at(sourceName);
		
		if(sourceList != nil){
			sourceList.do{|connection|
				connection.trigger;	
			}
		};
			
	}
	
	commenceHitch{|sourceName|
		var gui;
		gui = HitchGui.new(sourceName, this)
	}
	
	isVoiceCurrentlyLeadIng{|name|
		connections.postln;
		"name ".post; name.postln;
		"connections.at(name) ".post; connections.at(name).postln; 
		^(connections.at(name) != nil);
	}
	
	isVoiceInMasterChain{|parentName, childName|
		this.getChildren(parentName).do{|item|
			if(item == childName){
				^true
			};
			^this.isVoiceInMasterChain(item, childName);
		};
		^false;			
	}
	
	getChildren{|parentName|
		var sourceList, retList;
		retList = List.new;
		sourceList = connections.at(parentName);
		sourceList.do{|connection|
			retList.add(connection.getTargetName);
		};
		^retList;
	}
	
	addConnection{|sourceName, targetName, connectionType|
		var connectionClass, sourceList;
		
		sourceList = connections.at(sourceName);
		
		if(sourceList == nil){
			sourceList = Dictionary.new;
			connections.add(sourceName -> sourceList);
		};
		
		// DEFUALT CONNECTION TYPE
		if(connectionType == nil){
			connectionType = "Connection"
		};
		
		connectionClass = connectionType.interpret;
		sourceList.add(targetName -> connectionClass.new(sourceName, targetName, parent) );
	
	}
	
	freeAllHarnessed{|name|
		connections.removeAt(name);
	}
	
	getActiveVoiceNames{
		^parent.getActiveVoiceNames;
	}
	
	accept{|xb|
		xb.forConnectionManager(this);
		connections.keysValuesDo{|name, list|
			list.do{|conn|
				var connXb;
				connXb = XMLNodeBuilder.new;
				connXb.setParent(xb.getNode);
				conn.accept(connXb);
			}
		};
	}
	
}